package httpUtil;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * Created by wangcheng on 2014/7/29.
 */
public class HttpUtil {
    private static Logger logger = LoggerFactory.getLogger(HttpUtil.class);

    private static final String POST = "POST";
    private static final String GET = "GET";
    private static final String DELETE = "DELETE";
    private static final String PUT = "PUT";

    private static final String ENCODEING = "UTF-8";
    //private static final String BASE_URL = "http://mapi.test.etcp.cn/";
    //private static final String BASE_URL = "https://mapi.etcp.cn/";

//    private static final String BASE_URL = " http://106.15.81.17:7089/";
//    private static final String BASE_URL = "http://101.132.72.2:7089/";
//    private static final String BASE_URL = "http://101.132.146.129:7089/";
      //private static final String BASE_URL = "http://101.132.72.2:7089/";
//    private static final String BASE_URL = "http://101.132.72.2:7089/";
//    private static final String BASE_URL = "http://101.132.72.2:7089/";
    //private static final String BASE_URL = "http://106.15.81.17:7089/";
//    private static final String BASE_URL = "https://www.tankezuche.com:8443/";
//    private static final String BASE_URL = "http://10.1.3.243:8080/";
//    https://www.tankezuche.com:8443
//    private static final String BASE_URL = "http://www.tankezuche.com:7089/";
//    private static final String BASE_URL = "http://localhost:8080/";
//    private static final String BASE_URL = "http://www.tankezuche.com:7089/";
   private static final String BASE_URL = "http://localhost:9090/";
//    private static final String BASE_URL = "http://localhost:8080/";
//    private static final String BASE_URL = "http://101.132.146.129:7089/";
    //private static final String BASE_URL = "http://localhost:8080/";
//    private static final String BASE_URL = "http://localhost:8080/";
//    private static final String BASE_URL = "http://101.132.146.129:7089/";
//    private static final String BASE_URL = "https://www.tankezuche.com:8443/";
//    private static final String BASE_URL = "http://10.1.3.243:8080/";
    //private static final String BASE_URL = "http://www.tankezuche.com:7089/";
//    private static final String BASE_URL = "http://106.14.227.64:7089/";
//    private static final String BASE_URL = "http://106.15.81.17:7089/";
//    private static final String BASE_URL = "http://10.1.3.241:8080/";
    //private static final String BASE_URL = "http://101.132.146.129:7089/";
      //private static final String BASE_URL = "http://10.1.3.243:8080/";
//    private static final String BASE_URL = "http://114.55.11.127:7064/";
//    private static final String BASE_URL = "http://localhost:8082/";
//    private static final String BASE_URL = "http://localhost:8080/tanker/";
//    private static final String BASE_URL = "http://localhost:8080/";
//    private static final String BASE_URL = "http://localhost:8080/";
//    private static final String BASE_URL = "http://localhost:8080/app-server/";
//    private static final String BASE_URL = "http://localhost:8080/";
//    private static final String BASE_URL = "http://localhost:8080/";
//    private static final String BASE_URL = "http://localhost:8080/";
//    private static final String BASE_URL = "http://localhost:8080/app-server/";
//    private static final String BASE_URL = "http://localhost:8080/";
//    private static final String BASE_URL = "http://localhost:8080/";
//    private static final String BASE_URL = "http://localhost:8080/";
   // private static final String BASE_URL = "http://localhost:8082/";
//     private static final String BASE_URL = "http://localhost:8080/";
//    private static final String BASE_URL = "http://localhost:8080/";
//    private static final String BASE_URL = "http://10.0.3.213:7064/";
//    private static final String BASE_URL = "http://114.55.235.185:7064/";
// private static final String BASE_URL = "http://114.55.60.85/";
// private static final String BASE_URL = "http://10.0.3.207:7064/";
//    private static final String BASE_URL = "http://114.55.235.185:7064/";
// private static final String BASE_URL = "http://10.0.3.250:7064/";
//    private static final String BASE_URL = "http://114.55.235.185:7064/";
// private static final String BASE_URL = "http://10.0.3.250:7064/";
// private static final String BASE_URL = "http://10.0.3.205:7064/";
//    private static final String BASE_URL = "http://10.1.3.241:8080/";
//    private static final String BASE_URL = "http://114.55.11.127:7064/";

    public static HttpResult post(String reqUrl, Map<String, Object> reqMap) throws Exception{
    	System.out.println(reqUrl);
        ObjectMapper om = new ObjectMapper();
        String reqContent = om.writeValueAsString(reqMap);
        String result = send(reqUrl, reqContent, POST);
        System.out.println(result);
        //Gson gson = new Gson();
        //return gson.fromJson(result, HttpResult.class);
        return om.readValue(result, HttpResult.class);
    }

    public static String post22(String reqUrl, Map<String, Object> reqMap) throws Exception{
    	System.out.println(reqUrl);
        ObjectMapper om = new ObjectMapper();
        String reqContent = om.writeValueAsString(reqMap);
        String result = send(reqUrl, reqContent, POST);
        System.out.println(result);
        //Gson gson = new Gson();
        //return gson.fromJson(result, HttpResult.class);
        return result;
    }
    public static HttpResult delete(String reqUrl, Map<String, Object> reqMap) throws Exception{
    	ObjectMapper om = new ObjectMapper();
        String reqContent = om.writeValueAsString(reqMap);
        String result = send(reqUrl, reqContent, DELETE);
        return om.readValue(result, HttpResult.class);
    }

    public static HttpResult put(String reqUrl, Map<String, Object> reqMap) throws Exception{
    	ObjectMapper om = new ObjectMapper();
        String reqContent = om.writeValueAsString(reqMap);
        String result = send(reqUrl, reqContent, PUT);
        return om.readValue(result, HttpResult.class);
    }

    

    private static String send(String reqUrl, String reqContent, String method) throws Exception {
        String resContent = null;

        HttpURLConnection conn = null;
//        GZIPOutputStream out = null;
       OutputStream out = null;
//        GZIPInputStream in = null;
      InputStream in = null;
        BufferedReader reader = null;
        try {
            URL url = new URL(BASE_URL + reqUrl);
            conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(100000);
            conn.setReadTimeout(100000);
            System.out.println(url);
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            conn.setInstanceFollowRedirects(false);//是否自动处理重定向
            conn.setRequestMethod(method);
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("Content-Type", "application/json; charset=utf-8");//传递参数使用 &链接的表单提交方式
            //conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");//传递参数使用 &链接的表单提交方式
            conn.setRequestProperty("User-Agent", "AutoyolEs_web");
//            conn.setRequestProperty("Accept", "application/json;version=3.0;compress=false");
//            conn.setRequestProperty("User-Agent", null);

            conn.connect();
            if (!method.equals(GET)) {
//            	conn.setRequestProperty("Accept", null);
//                out = new GZIPOutputStream(conn.getOutputStream());
            	out = conn.getOutputStream();
                //发送请求数据
                out.write(reqContent.getBytes(ENCODEING));
                out.flush();
                out.close();
            }
            //接收返回数据
            int resCode = conn.getResponseCode();
            if(resCode == 200){
                in = conn.getInputStream();
                reader = new BufferedReader(new InputStreamReader(in, ENCODEING));
                resContent = reader.readLine();
            }else{
                System.out.println("服务器返回码："+resCode);
            }
        } catch (Exception e) {
            throw e;
        } finally{
            if(reader != null){
                reader.close();
            }
            if(in != null){
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
			if(out != null){
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
            if(conn != null){
                conn.disconnect();
            }
        }
        return resContent;
    }
    /**
     * 参数拼接
     * @param body
     * @return
     */
    public static String getPamStr(Map<String, Object> body) {
		String urel="?";
		Set<String> key=body.keySet();
		for (String string : key) {
			urel+=string+"="+body.get(string).toString()+"&";
		}
		urel=	urel.substring(0,urel.length()-1);
		return urel;
	}
    public static void main(String[] args) throws Exception {
       //HttpResult httpResult = get("/car/v4/list?lon=0.000000&lat=0.000000&gbType=0&carType=0&seq=0&pageNum=1&pageSize=10&token=0&startTime=0&endTime=0&brandId=0");
    }
}
